package com.example.newsdaily.slice;

import com.alibaba.fastjson.JSON;
import com.example.newsdaily.ResourceTable;
import com.example.newsdaily.adapter.CommonProvider;
import com.example.newsdaily.adapter.ViewHolder;
import com.example.newsdaily.entity.ItemImage;
import com.example.newsdaily.entity.TBriefNews;
import com.example.newsdaily.provider.SwiperPageProvider;
import com.example.newsdaily.utl.ContainUtil;
import com.example.newsdaily.utl.HttpClientUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.eventhandler.EventRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class DiscoverAbilitySlice extends AbilitySlice {
    EventRunner eventRunner;
    Text pageTitle;
    Timer timer;
    int currentPage = 0;
    static final int SWITCH_INTERVAL = 3000;
    PageSlider swiperSlider;
//    Button button;

    List<TBriefNews> tBriefNewsList = new ArrayList<>();
    ListContainer discoverListContainer;
    CommonProvider<TBriefNews> discoverCommonProvider;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_discover);

        swiperSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
        List<ItemImage> list = getData();
        SwiperPageProvider pageProvider = new SwiperPageProvider(list,this);
        swiperSlider.setProvider(pageProvider);

        PageSliderIndicator indicator = (PageSliderIndicator)findComponentById(ResourceTable.Id_indicator);
        ShapeElement normalElement = new ShapeElement();
        normalElement.setRgbColor(RgbColor.fromArgbInt(0x808080));
        normalElement.setAlpha(250);
        normalElement.setShape(ShapeElement.RECTANGLE);
        normalElement.setBounds(0, 0, 16, 16);
        ShapeElement selectedElement = new ShapeElement();
        selectedElement.setRgbColor(RgbColor.fromArgbInt(0x242424));
        selectedElement.setAlpha(250);
        selectedElement.setShape(ShapeElement.RECTANGLE);
        selectedElement.setBounds(0, 0, 24, 24);
        indicator.setItemElement(normalElement, selectedElement);
        indicator.setItemOffset(60);
        indicator.setPageSlider(swiperSlider);

        List<String> listTitle = getTitle();
        pageTitle = (Text) findComponentById(ResourceTable.Id_page_slider_title);

        timer = new Timer();
        startAutoSwitch();

        swiperSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {

            }

            @Override
            public void onPageSlideStateChanged(int i) {

            }

            @Override
            public void onPageChosen(int i) {
                pageTitle.setText(listTitle.get(i));

            }
        });

        discoverListContainer = (ListContainer) findComponentById(ResourceTable.Id_other_news);

        update();

//        button = (Button) findComponentById(ResourceTable.Id_button);
//        button.setClickedListener(new Component.ClickedListener() {
//            @Override
//            public void onClick(Component component) {
//                Intent intent = new Intent();
//                Operation operation = new Intent.OperationBuilder()
//                        .withDeviceId("")
//                        .withBundleName("com.example.newsdaily")
//                        .withAbilityName("com.example.newsdaily.CollectionAbility")
//                        .build();
//                intent.setOperation(operation);
//                startAbility(intent);
//            }
//        });

        discoverListContainer.setItemSelectedListener(new ListContainer.ItemSelectedListener() {
            @Override
            public void onItemSelected(ListContainer listContainer, Component component, int i, long l) {
                Intent intent1 = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName("com.example.newsdaily")
                        .withAbilityName("com.example.newsdaily.NewsDetailAbility")
                        .build();
                intent1.setOperation(operation);
                intent1.setParam("id", tBriefNewsList.get(i).getId());
                startAbility(intent1);
            }
        });
    }

    private void startAutoSwitch() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                getUITaskDispatcher().asyncDispatch(()->{
                    currentPage = (currentPage+1)%5;
                    swiperSlider.setCurrentPage(currentPage);
                });
            }
        },0,SWITCH_INTERVAL);
    }

    private List<String> getTitle() {
        List<String> list = new ArrayList<>();
        list.add(new String("丝路电商班列（西安—乌鲁木齐）开行突破100列"));
        list.add(new String("甘肃肃南：夏日祁连山国家公园景色迷人"));
        list.add(new String("投资天津丨镜头直击“七彩码头”之美"));
        list.add(new String("新疆布尔津迎来旅游旺季"));
        list.add(new String("2024全球数字经济大会开幕"));

        return list;
    }

    private List<ItemImage> getData() {
        List<ItemImage> list = new ArrayList<>();
        list.add(new ItemImage(ResourceTable.Media_swiper01));
        list.add(new ItemImage(ResourceTable.Media_swiper02));
        list.add(new ItemImage(ResourceTable.Media_swiper03));
        list.add(new ItemImage(ResourceTable.Media_swiper04));
        list.add(new ItemImage(ResourceTable.Media_swiper05));
        return list;
    }

    public void update() {
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        // 从数据库中得到所有新闻
                        String result = HttpClientUtil.doGet(ContainUtil.FIND_BRIEF_NEWS);
                        tBriefNewsList = JSON.parseArray(result, TBriefNews.class);
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {

                                discoverCommonProvider = new CommonProvider<TBriefNews>(tBriefNewsList, getContext(), ResourceTable.Layout_other_news_item) {
                                    @Override
                                    protected void convert(ViewHolder holder, TBriefNews item, int position) {
                                        holder.setImageResource(ResourceTable.Id_other_image, ContainUtil.detail_pic_id[item.getPicId()]);
                                        holder.setText(ResourceTable.Id_other_title, item.getTitle());
                                        holder.setText(ResourceTable.Id_other_content, item.getContent());
                                        holder.setText(ResourceTable.Id_other_publisher, item.getPublisher());
                                    }
                                };
                                discoverListContainer.setItemProvider(discoverCommonProvider);
                            }
                        });
                    }
                }
        ).start();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (timer != null) {
            timer.cancel();
            timer=null;
        }
    }
}
